
from ScoreTransformer import *
from function import *
import time
import pandas as pd
from SqlConnect import *



def green_model_score(lst,mysql_flag = True):



    if mysql_flag:
        db = Sql()
        dff = get_dff(lst,db)
        if len(dff) == 0:
            print(dff)
            return pd.DataFrame({'pjuuid':[''],'info':['无尽调数据无法评价']})
    else:
        dff = pd.read_excel('./data/index_data.xlsx',sheet_name='Sheet2') #.iloc[[0]]

    dff = dff.drop_duplicates(['pjuuid'])


    dfsc = pd.read_excel('./data/dfsc.xlsx',sheet_name='dfsc')
    dfwt = pd.read_excel('./data/dfwt.xlsx')


    #保存pjuuid与id_number 的映射关系

    id_hander = dff[['pjuuid','credit_id','pripid']]
    del dff['credit_id']
    del dff['pripid']

    model_type_lst = get_model_type_list(dfsc)

    print('转换数据类型')
    dff = convert_feature_type(dff,dfsc)
    print(len(dff),'-----------------------------')

    dfs = pd.DataFrame()
    for model_type in model_type_lst:

        #特征 权重 分数 切片

        dff_cut = dff.loc[dff.model_type == model_type]

        if len(dff_cut) == 0:
            print(f'{model_type}该模型下无客户跳过了')
            continue

        dfsc_cut = dfsc.loc[dfsc.model_type.isin(['all',model_type])]
        dfwt_cut = dfwt.loc[dfwt.model_type.isin(['all',model_type])]


        #分数转换
        dfs_cut = transform_value_to_score(dfsc_cut,dff_cut)
        #获取esg分数
        esg_score_cut = get_esg_score_cut(dfs_cut,dfwt_cut)  # weight_score   +  esgscore_cut
        #获取认绿分数
        rl_score = get_rl_score(dfs_cut,dff_cut)

        # print(dfs_cut)
        # print(dff_cut)

        #获取最终分数
        esg_rl = pd.merge(esg_score_cut[['pjuuid','model_type','esg_score']],rl_score,on = 'pjuuid')
        esg_rl['score'] = esg_rl[['esg_score','rl_score']].sum(axis=1)


        #合并
        dfs = pd.concat([dfs,esg_rl])

    if len(dfs) == 0:
        result = dff.copy()
        result['info'] = '行业不在评价范围内'
        return result[['pjuuid','info']]

    #增加等级
    result = get_level(dfs)

    #增加info信息
    all_result = add_info(result,id_hander)

    print(all_result.T)
    all_result.to_excel('./result.xlsx',index=False)


    return all_result

    # db.ToSql(all_result,'table_name')

# print(green_model_score(lst).T)